/**
 * @资源路由
 * api.get('/index', IndexController.index)
 * api.get('/index/create', IndexController.create)
 * api.post('/index', IndexController.store)
 * api.get('/index/:id', IndexController.show)
 * api.get('/index/:id/edit', IndexController.edit)
 * api.put('/index/:id', IndexController.save)
 * api.get('/index/:id/edit', IndexController.destroy)
 * 
 */
const views = require('koa-views')
const Router = require('koa-router')()
const BootcdnController = require('../app/Controllers/BootcdnController')
const OauthClientController = require('../app/Controllers/Oauth/OauthClientController')
const OauthController = require('../app/Controllers/Oauth/OauthController')
const AuthController = require('../app/Controllers/Auth/AuthController')
const IndexController = require('../app/Controllers/Index/IndexController')
const auth = require('../app/Middlewares/Web')
// Must be used before any router is used
Router.use(views(__dirname + '/../resource/views', {
	map: {
		html: 'underscore'
	},
	extension: 'pug'
}))
class Web {
    constructor() {
        this.$web = Router
        this.$web.use(auth)        
        this.init()
        this.routes()
        return this.$web
    }

    /**
     * 初始化路由 加载资源路由
     * 
     * @memberof Api
     */
    async init () {
        await this.resource('bootcdn', BootcdnController)
        await this.resource('oauth/client', OauthClientController)
    }
    // 定义普通路由
    async routes() {
        // 登录注册  Oauth
        this.$web.get('/', IndexController.index)
        this.$web.get('/signin', AuthController.signin)
        this.$web.post('/signin', AuthController.signin)
        this.$web.get('/signup', AuthController.signup)
        this.$web.post('/signup', AuthController.signup)
        this.$web.get('/signout', AuthController.signout)
        this.$web.get('/oauth/authorize', OauthController.authorize)
        this.$web.post('/oauth/authorize', OauthController.authorize)
        this.$web.post('/oauth/token', OauthController.token)
        
    }

    /**
     * 生成资源路由
     * 
     * @param {any} name 
     * @param {any} controller 
     * @memberof Web
     */
    async resource (name, controller) {
        this.$web.get(`/${name}`, controller.index)
        this.$web.get(`/${name}/create`,  controller.create)
        this.$web.post(`/${name}`,  controller.store)
        this.$web.get(`/${name}/:id`,  controller.show)
        this.$web.get(`/${name}/:id/edit`,  controller.edit)
        this.$web.post(`/${name}/:id`,  controller.save)
        this.$web.get(`/${name}/:id/destroy`,  controller.destroy)
    }
    
}

module.exports = new Web()
